package com.example.bbang.controller;

import com.example.bbang.common.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("upload")
public class UploadController {

//    @Value("C://后端//Bbang//src//main//resources//static//img")
    @Value("/www/wwwroot/bangbangTest/img/")
    private String dirPath;

//    @Value("${upload.imgUrl:http://localhost:8080/bang/img/}")
//    private String imgUrl;

    @PostMapping("img")
    public CommonResult addimg(@RequestParam("tupian") List<MultipartFile> tupian, HttpServletRequest request) {
        String newFilename = null; // 声明在方法最外层

        // 判断所上传文件是否存在
        if (!tupian.isEmpty() && tupian.size() > 0) {
            // 循环输出上传的文件
            for (MultipartFile file : tupian) {
                // 获取上传文件的原始名称
                String originalFilename = file.getOriginalFilename();
                System.out.println("=========originalFilename=" + originalFilename);
                // 使用绝对路径

                String absoluteDirPath = dirPath;
                File filePath = new File(absoluteDirPath);
                System.out.println("=========dirPath=" + absoluteDirPath);

                // 如果保存文件的地址不存在，就先创建目录
                if (!filePath.exists()) {
                    System.out.println("==========");
                    filePath.mkdirs();
                }

                // 使用UUID（通用唯一标识）重新命名上传的文件名称
                newFilename = UUID.randomUUID() + originalFilename;
                System.out.println("=========newFilename=" + newFilename);

                try {
                    // 使用MultipartFile接口的方法完成文件上传到指定位置
                    file.transferTo(new File(absoluteDirPath, newFilename));
                    System.out.println(absoluteDirPath + newFilename);
                    return CommonResult.ok(newFilename);
                } catch (Exception e) {
                    e.printStackTrace();
                    return CommonResult.ok("nothing");
                }
            }
        } else {
            System.out.println("nothing");
            return CommonResult.ok("nothing,可能是本地后端上传的");
        }

        return CommonResult.ok(newFilename);
    }
}